package com.bplow.deep.stock.service.Impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bplow.deep.base.pagination.Page;
import com.bplow.deep.base.utils.DateUtils;
import com.bplow.deep.base.velocity.VelocityUtils;
import com.bplow.deep.stock.domain.SkCustomerWarn;
import com.bplow.deep.stock.domain.SkSendSmsLog;
import com.bplow.deep.stock.domain.SkWarehousePositon;
import com.bplow.deep.stock.domain.SkWarnLog;
import com.bplow.deep.stock.domain.SkWarnRule;
import com.bplow.deep.stock.mapper.SkSendSmsLogMapper;
import com.bplow.deep.stock.mapper.SkWarehousePositonMapper;
import com.bplow.deep.stock.mapper.SkWarnLogMapper;
import com.bplow.deep.stock.mapper.SkWarnRuleMapper;
import com.bplow.deep.stock.service.CustomerWarnService;
import com.bplow.deep.stock.service.ExecuteRuleScriptService;
import com.bplow.deep.stock.service.QueryStockPriceRealTimeSerivce;
import com.bplow.deep.stock.service.ScriptService;
import com.bplow.deep.stock.service.SendMessageService;
import com.bplow.deep.stock.service.SystemUserService;
import com.bplow.deep.stock.vo.Message;
import com.bplow.deep.stock.vo.StockInfo;
import com.bplow.deep.sysmng.domain.SysUser;

/**
 * 
 * @desc
 * @author qian
 * @date 2019年3月24日 上午9:49:50
 */
@Service("ExecuteRuleScriptImpl")
public class ExecuteRuleScriptImpl implements ExecuteRuleScriptService, InitializingBean {

	Logger logger = LoggerFactory.getLogger(this.getClass());
	
	Map<String, SkWarnRule> rulesMap = new ConcurrentHashMap<String, SkWarnRule>();
	
	List<SkCustomerWarn> warns = new ArrayList<SkCustomerWarn>(0);

	@Autowired
	private CustomerWarnService customerWarnService;

	@Autowired
	private QueryStockPriceRealTimeSerivce queryStockPriceRealTimeSerivce;

	@Autowired
	SkWarehousePositonMapper skWarehousePositonMapper;
	
	@Autowired
	private SkWarnRuleMapper skWarnRuleMapper;
	
	@Autowired
	private ScriptService scriptService;
	
	@Autowired
	private SystemUserService systemUserService;
	
	@Autowired
	private SkWarnLogMapper skWarnLogMapper;
	
	@Autowired
	private SkSendSmsLogMapper skSendSmsLogMapper;
	
	@Autowired
	private SendMessageService sendMessageService;

	@Override
	public void execute() {

		//获取系统所有规则
		List<SkCustomerWarn> warns = this.warns;

		for (SkCustomerWarn warn : warns) {
			
			if ("0".equals(warn.getStatus())) {// 该规则已命中，跳到下一个规则
				continue;
			}

			String stockId = warn.getStockId();
			String userId = warn.getUserId();
			String scriptId = warn.getRuleId();
			
			// 获取用户信息
			SysUser user = new SysUser();
			user.setUserId(userId);
			user = systemUserService.queryUser(user);
			
			// 获取股票信息
			SkWarehousePositon position = skWarehousePositonMapper.selectByPrimaryKey(stockId);

			// 实时获取股票价格
			StockInfo aimStock = queryStockPriceRealTimeSerivce.getStockInfoMap().get(position.getStockName());
			
			if(aimStock == null){
				logger.error("沒有獲取到{}實時價格",stockId);
				continue;
			}

			//执行规则脚本
			Map<String, Serializable> parament = new HashMap<String, Serializable>();

			parament.put("currentPrice", aimStock.getCurrentPrice());//当前价格
			parament.put("wave", aimStock.getWave().abs());//波动值abs
			parament.put("waveValue", aimStock.getWave());//波动值
			parament.put("exceptValue", warn.getValue());//目标值
			
			SkWarnRule warnRule = rulesMap.get(scriptId);
			
			if (null == warnRule || StringUtils.isBlank(warnRule.getScripte())) {
				break;
			}
			
			boolean result = scriptService.executeScripte(warnRule.getScripte(), parament);
			
			if (result) {// 命中规则
				
				warn.setStatus("0");

				// 发送短信
				if (null != user && StringUtils.isNotBlank(user.getMobile())) {
					// 短信描述信息
					String message = VelocityUtils.evaluate(parament, warnRule.getRuleMsg());
					SkSendSmsLog smsLog = new SkSendSmsLog();

					smsLog.setSmsId(UUID.randomUUID().toString().replace("-", ""));
					smsLog.setSendMobile(user.getMobile());
					smsLog.setSendCnt(message);
					skSendSmsLogMapper.insert(smsLog);

					Message msg = new Message();
					msg.setMobile(user.getMobile());

					Map<String, Serializable> smsParam = new HashMap<String, Serializable>();

					smsParam.put("taskId", "ds" + stockId);
					smsParam.put("taskName", message);
					smsParam.put("date", DateUtils.getShortDay());
					msg.setParament(smsParam);

					sendMessageService.sendMessage(msg);

					// 记录日志
					SkWarnLog skWarnLog = new SkWarnLog();
					skWarnLog.setId(UUID.randomUUID().toString().replace("-", ""));
					skWarnLog.setUserId(userId);
					skWarnLog.setStockId(stockId);
					skWarnLog.setRuleId(warn.getRuleId());
					skWarnLog.setWarnMsg(message);
					skWarnLogMapper.insert(skWarnLog);
				}
			}
			
			
		}

	}

	@Override
	public void afterPropertiesSet() throws Exception {
		// 获取所有规则定义
		SkWarnRule skWarnRule = new SkWarnRule();
		skWarnRule.setPageSize(10000);
		Page<SkWarnRule> rulePage = skWarnRuleMapper.queryForPage(skWarnRule);

		List<SkWarnRule> warnRules = rulePage.getDatas();

		for (SkWarnRule rule : warnRules) {
			rulesMap.put(rule.getRuleId(), rule);
		}
		
		this.warns = customerWarnService.obtainAllUserStockId();

	}

}
